package cn.czh.controller;

import cn.czh.core.AjaxResult;
import cn.czh.entity.Admin;
import cn.czh.entity.Teacher;
import cn.czh.exception.BaseException;
import cn.czh.service.AdminService;
import cn.czh.service.TeacherService;
import cn.czh.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author czh
 * @since 2021-06-01
 */

@CrossOrigin(origins = "http://localhost:8080", maxAge = 3600)
@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    AdminService adminService;
    @Autowired
    TeacherService teacherService;
    @PostMapping("/admin")
    public AjaxResult adminLogin(@RequestBody Admin admin){
        AjaxResult ajaxResult =AjaxResult.success();
        if (StringUtils.isNotNull(admin)) {
            if (admin.getUsername() != null && !admin.getUsername().equals("") && admin.getPassword() != null && !admin.getPassword().equals("")) {
                int login = adminService.login(admin);
                if (login == 0) {
                    throw new BaseException("用户不存在！");
                }
                if (login == 1) {
                    throw new BaseException("密码错误！");
                }
                ajaxResult.put("token","czhAdminLoginToken");
                return ajaxResult;
            }
            throw new BaseException("传入参数错误！");
        }
        throw new BaseException("传入参数错误！");
    }
    @PostMapping("/teacher")
    public AjaxResult teacherLogin(@RequestBody Teacher teacher) {
        AjaxResult ajaxResult = AjaxResult.success();
        if (StringUtils.isNotNull(teacher)) {
            if (teacher.getUsername() != null && !teacher.getUsername().equals("") && teacher.getPassword() != null && !teacher.getPassword().equals("")) {
                int login = teacherService.login(teacher);
                if (login == 0) {
                    throw new BaseException("用户不存在！");
                }
                if (login == 1) {
                    throw new BaseException("密码错误！");
                }
                ajaxResult.put("token","czhTeacherLoginToken");
                Integer teacherId = teacherService.getTeacherId(teacher.getUsername());
                ajaxResult.put("teacherId",teacherId);
                return ajaxResult;
            }
            throw new BaseException("传入参数错误！");
        }
        throw new BaseException("传入参数错误！");
    }
}
